package com.familytree.controller;

import com.familytree.common.exception.BusinessException;
import com.familytree.common.response.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/files")
@RequiredArgsConstructor
public class FileController {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.allowed-types}")
    private String allowedTypes;

    @Value("${file.upload.max-size}")
    private long maxSize;

    @Value("${app.base-url:http://localhost:8080}")
    private String baseUrl;

    @GetMapping("/uploads/{filename:.+}")
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
        try {
            Path file = Paths.get(uploadPath).resolve(filename);
            Resource resource = new UrlResource(file.toUri());
            
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
            } else {
                throw new BusinessException("Could not read file: " + filename);
            }
        } catch (MalformedURLException e) {
            throw new BusinessException("Could not read file: " + filename);
        }
    }

    @PostMapping("/upload")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件类型
            String fileType = file.getContentType();
            if (fileType == null || !isAllowedFileType(fileType)) {
                throw new BusinessException("不支持的文件类型");
            }

            // 检查文件大小
            if (file.getSize() > maxSize) {
                throw new BusinessException("文件大小超过限制");
            }

            // 创建上传目录
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String filename = UUID.randomUUID() + extension;

            // 保存文件
            Path filePath = uploadDir.resolve(filename);
            Files.copy(file.getInputStream(), filePath);

            // 返回文件信息
            Map<String, Object> data = new HashMap<>();
            data.put("fileName", filename);
            data.put("fileUrl", baseUrl + "/api/files/uploads/" + filename);
            data.put("fileType", fileType);
            data.put("fileSize", file.getSize());

            return Result.success(data);
        } catch (IOException e) {
            throw new BusinessException("文件上传失败：" + e.getMessage());
        }
    }

    private boolean isAllowedFileType(String fileType) {
        return allowedTypes.contains(fileType);
    }
} 